<%--
  Created by IntelliJ IDEA.
  User: YNA-User
  Date: 2019/12/23
  Time: 9:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<link href='../css/fullcalendar.css' rel='stylesheet' />
<link href='../css/fullcalendar.print.css' rel='stylesheet' media='print' />
<script src='../javascript/moment.min.js'></script>
<script src='../javascript/jquery.min.js'></script>
<script src='../javascript/fullcalendar.js'></script>
<script src='../javascript/customTimeControls.js'></script>
<%--<script src='../javascript/local/zh-cn.js'></script>--%>
<script>

    var objStartTime = {number: 6.5, hour: 6, minute: 30, toString: '6:30'};
    var objEndTime = {number: 22.5, hour: 22, minute: 30, toString: '22:30'};
    // 午休设置
    var objLunchBreak = {lunchStart: 12, lunchEnd: 14};

    var initRowHeight = 21;

    function dateFormat(fmt, date) {
        var ret;
        var opt = {
            "Y+": date.getFullYear().toString(),        // 年
            "M+": (date.getMonth() + 1).toString(),     // 月
            "D+": date.getDate().toString(),            // 日
            "H+": date.getHours().toString(),           // 时
            "m+": date.getMinutes().toString(),         // 分
            "s+": date.getSeconds().toString()          // 秒
            // 有其他格式化字符需求可以继续添加，必须转化成字符串
        };
        for (var k in opt) {
            ret = new RegExp("(" + k + ")").exec(fmt);
            if (ret) {
                fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
            }
        }
        return fmt;
    }

    $(document).ready(function () {

        $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            height: 'parent',
            // defaultDate: '2017-10-12',
            defaultView: "agendaWeek",
            //slotDuration: '00:30:00',
            slotLabelInterval: 0, // 左侧时间间隔
            navLinks: true, // can click day/week names to navigate views
            editable: true,
            eventLimit: true, // allow "more" link when too many events
            businessHours: {
                dow: [0, 1, 2, 3, 4, 5, 6],
                start: objStartTime.toString,
                end: objEndTime.toString
            },
            selectable: true,
            selectHelper: true,
            eventConstraint: "businessHours", // 设置事件可拖拽区域
            selectConstraint: "businessHours", // 设置事件可点击区域
            allDaySlot: false,
            titleFormat: 'YYYY/MM/DD', // 日历每列头部的文字
            slotLabelFormat: 'h(:mm)a',
            // local: 'zh-cn',
            // firstDay: 1,
            eventAfterAllRender: event_after_all_rendar,
            eventDrop: event_drop,
            eventResize: event_resize,
            selectAllow : select_allow,
            select: select_add,
            eventClick: event_click,
            events: default_events
        });

    });


    function tempClose() {
        // 关闭
        $("#myClose").on('click', function () {
            $("div[id='showDiv']").css('display', 'none');
        });

    }


    /**
     * 当所有事件渲染完成后触发
     * @param view
     */
    function event_after_all_rendar(view) {
        // 手动设置午休样式
        var topHeight = getLunchHeight(objLunchBreak.lunchStart) + "px";
        var bottomHeight = "-" + getLunchHeight(objLunchBreak.lunchEnd) + "px";
        $('div[class="fc-business-container"]').each(function(index, el) {
            if ($(el).find('div[lunch="1"]').length > 0) {
                $(el).find('div[lunch="1"]').remove();
            }
            $(el).append('<div class="fc-nonbusiness fc-bgevent" lunch="1" style="top: '+ topHeight +'; bottom: '+ bottomHeight +';"></div>');
        });
    }

    /**
     * 获取lunch高度
     */
    function getLunchHeight(time) {
        var eventHeight = 0;
        for (var i = 0; i < time; i+=0.5) {
            eventHeight += initRowHeight;
        }
        return eventHeight;
    }
    

    /**
     * 当拖动结束且日程移动另一个时间时触发
     * @param event
     * @param delta
     * @param revertFunc
     */
    function event_drop(event, delta, revertFunc) {
        $.ajax({
            url: 'updateEventById',
            dataType: 'json',
            data: {
                id: event.id,
                startTime: event.start.format('YYYY-MM-DD HH:mm:ss'),
                endTime: event.end.format('YYYY-MM-DD HH:mm:ss')
            },
            success: function (result) {
                if (result.msg === 'success') {
                    alert('更新成功!');
                }
            },
            error: function () {
                alert('更新失败!');
                // 如果被调用的话，日程会恢复到拖拽前的时间（被还原）
                revertFunc();
            }
        });
    }


    /**
     * 当日程事件调整（resize）结束并且事件被改变时触发
     * @param event
     * @param delta
     * @param revertFunc
     */
    function event_resize(event, delta, revertFunc) {

        $.ajax({
            url: 'updateEventById',
            dataType: 'json',
            data: {
                id: event.id,
                endTime: event.end.format('YYYY-MM-DD HH:mm:ss')
            },
            success: function(result) {
                if (result.msg === 'success') {
                    alert('更新成功!');
                }
            },
            error: function () {
                alert('更新失败!');
                // 如果被调用的话，日程会恢复到拖拽前的时间（被还原）
                revertFunc();
            }
        });
    }


    /**
     * 可不可以点击主要是通过这个方法来限定，返回false就不能点击
     * @param clickInfo
     * @returns {boolean}
     */
    function select_allow(clickInfo) {
        var start = clickInfo.start.format('YYYYMMDDHHmmss');
        var num = clickInfo.start.format('HH:mm').split(":");
        var startNum = Number(num[0]) + (Number(num[1]) / 60);
        // 现在时间
        var time = dateFormat("YYYYMMDDHHmmss", new Date());
        if (start <= time) {
            alert('事件不能在过去时间创建');
            return false;
        }
        if (startNum >= objLunchBreak.lunchStart && startNum <= objLunchBreak.lunchEnd) {
            alert('事件不能在午休时间创建');
            return false;
        }
    }


    /**
     * 添加新事件
     * @param start
     * @param end
     */
    function select_add(start, end) {
        document.getElementById("myForm").reset();

        // 给下拉框赋值
        var objDate = {
            startDate: start.format("YYYY-MM-DD"),
            endDate: end.format("YYYY-MM-DD")
        };
        assignment(null, objStartTime, objEndTime, objDate);

        $("#selectStartTime").val(start.format("HH:mm"));
        $("#selectEndTime").val(end.format("HH:mm"));
        $("#myInsert").css('display', 'block');
        $("#myDelete").css('display', 'none');
        $("#myUpdate").css('display', 'none');
        $("div[id='showDiv']").css('display', 'block');

        // TODO .on('click', function () {}) 点击一次 click 会进多次方法, 造成多次添加事件数据, 未找到原因, 暂时用 flag 标识
        var flag = true;
        $("#myInsert").on('click', function () {
            if (flag) {
                var eventData = {
                    title: $("input[name='title']").val(),
                    startTime: $("#selectStartTime").attr("start_date") + " " + $("#selectStartTime").val(),
                    endTime: $("#selectEndTime").attr("end_date") + " " + $("#selectEndTime").val()
                };

                $.ajax({
                    url: "addMyEvent",
                    data: eventData,
                    type: "POST",
                    dataType: "json",
                    success: function (result) {
                        eventData.id = result.id;
                        eventData.start = eventData.startTime;
                        eventData.end = eventData.endTime;
                        $("div[id='showDiv']").css('display', 'none');
                        // 添加事件
                        $('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
                    },
                    error: function () {
                        alert('事件添加失败!');
                    }
                });
                $('#calendar').fullCalendar('unselect');
                flag = false;
            }
        });
        tempClose();
    }

    /**
     * 点击单个事件触发, 执行修改, 更新操作
     * @param calEvent 事件对象
     * @param jsEvent js事件对象(坐标信息等)
     * @param view 视图(天, 周, 月)
     */
    function event_click(calEvent, jsEvent, view) {
        // 给下拉框赋值
        var objDate = {
            startDate: calEvent.start.format("YYYY-MM-DD"),
            endDate: calEvent.end.format("YYYY-MM-DD")
        };
        assignment(null, objStartTime, objEndTime, objDate);

        $("input[name='id']").val(calEvent.id);
        $("input[name='title']").val(calEvent.title);
        $("#selectStartTime").val(calEvent.start.format("HH:mm"));
        $("#selectEndTime").val(calEvent.end.format("HH:mm"));

        // 设置按钮隐藏
        $("#myInsert").css('display', 'none');
        $("#myDelete").css('display', 'block');
        $("#myUpdate").css('display', 'block');
        $("div[id='showDiv']").css('display', 'block');

        // 删除
        $("#myDelete").on('click',  calEvent, function(event){
            // 火狐 event 解决方式
            var e = event || window.event;
            event.stopPropagation();
            $.ajax({
                url: 'deleteEventById',
                dataType: 'json',
                data: {
                    id: calEvent.id
                },
                success: function(result) {
                    if (result.msg === 'success') {
                        alert('删除成功!');
                        $("div[id='showDiv']").css('display', 'none');
                        $("#calendar").fullCalendar("removeEvents", calEvent.id);
                    }
                },
                error: function () {
                    alert('删除失败!');
                }
            });

        });

        // 更新
        $("#myUpdate").on('click', calEvent, function (event) {
            var startNum = Number($("#selectStartTime").val().toString().split(":")[0]) + (Number($("#selectStartTime").val().toString().split(":")[1]) / 60);
            var endNum = Number($("#selectEndTime").val().toString().split(":")[0]) + (Number($("#selectEndTime").val().toString().split(":")[1]) / 60);

            if (!((startNum < objLunchBreak.lunchStart || startNum >= objLunchBreak.lunchEnd)
                && (endNum <= objLunchBreak.lunchStart || endNum > objLunchBreak.lunchEnd))) {
                alert('事件不能在午休时间创建');
                return;
            }

            // 火狐 event 解决方式
            var e = event || window.event;
            event.stopPropagation();
            calEvent.id = $("input[name='id']").val();
            calEvent.title = $("input[name='title']").val();
            calEvent.start = $("#selectStartTime").attr("start_date") + " " + $("#selectStartTime").val();
            calEvent.end = $("#selectEndTime").attr("end_date") + " " + $("#selectEndTime").val();
            $.ajax({
                url: 'updateEventById',
                dataType: 'json',
                data: {
                    id: calEvent.id,
                    title: calEvent.title,
                    startTime: calEvent.start,
                    endTime: calEvent.end
                },
                success: function(result) {
                    if (result.msg === 'success') {
                        alert('更新成功!');
                        $("div[id='showDiv']").css('display', 'none');
                        $("#calendar").fullCalendar("updateEvent", calEvent);
                    }
                },
                error: function () {
                    alert('更新失败!');
                }
            });

        });
        tempClose();
    }


    /**
     * 默认加载事件数据源
     * @param start
     * @param end
     * @param timezone
     * @param callback
     */
    function default_events(start, end, timezone, callback) {
        // 默认查询从 start - end 时间段(根据 显示的视图)的所有 event
        $.ajax({
            url: 'getAllEventByTime',
            dataType: 'json',
            data: {
                startTime: start.format('YYYY-MM-DD HH:mm:ss'),
                endTime: end.format('YYYY-MM-DD HH:mm:ss')
            },
            success: function(result) {
                var events = [
                    {
                        // 实时设置过去时间背景, 以及不能被拖动
                        title: 'old event',
                        start: '1999-01-01T13:13:55-0400',
                        end: new Date(),
                        overlap: false,
                        rendering: 'background',
                        color: '#EEB4B4'
                    }
                ];
                $(result).each(function() {
                    var tempEvent = {};
                    tempEvent.id = this.id;
                    tempEvent.title = this.title;
                    tempEvent.start = this.startTime;
                    tempEvent.end = this.endTime;
                    tempEvent.color = this.eventStatus;
                    if (this.startTime < dateFormat("YYYY-MM-DD HH:mm:ss", new Date())){
                        tempEvent.startEditable = false; // 禁止单个 event 开始时间的移动
                        tempEvent.durationEditable = false; // 禁止单个 event 结束时间的移动
                    }
                    events.push(tempEvent);
                });
                callback(events);
            }
        });
    }



    /**
     * 事件拖 拉时间包含午休 返回 false
     * @param startMs
     * @param endMs
     */
    function lunchContainsRange(startMs, endMs) {
        var eventTimes = [];
        var flag = true;
        var strStartMs = dateFormat('HH:mm', startMs).split(":");
        var strEndMs = dateFormat('HH:mm', endMs).split(":");
        var startNum = Number(strStartMs[0] - 8) + Number(strStartMs[1] / 60);
        var endNum = Number(strEndMs[0] - 8) + Number(strEndMs[1] / 60);

        for (var i = (strStartMs[0] - 8); i <= (strEndMs[0] - 8); i++) {
            eventTimes.push(i);
        }
        for (var j = (objLunchBreak.lunchStart + 1); j < objLunchBreak.lunchEnd; j++) {
            if ($.inArray(j, eventTimes) !== -1) {
                flag = false;
                break;
            }
        }
        return (startNum < objLunchBreak.lunchStart || startNum >= objLunchBreak.lunchEnd)
            && (endNum <= objLunchBreak.lunchStart || endNum > objLunchBreak.lunchEnd) && flag;
    }


</script>
<style>
    html,
    body {
        overflow: hidden;
        /* don't do scrollbars */
        font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
        font-size: 14px;
    }

    #calendar-container {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
    }

    .fc-header-toolbar {
        /*
        the calendar will be butting up against the edges,
        but let's scoot in the header's buttons
        */
        padding-top: 1em;
        padding-left: 1em;
        padding-right: 1em;
    }
</style>
</head>

<body>

<div id='calendar-container'>
    <div id='calendar'></div>
</div>


<div id="showDiv"
     style="display: none;width: 300px;height: 200px;background-color: aquamarine;position: absolute;top: 19px;z-index: 999;">
    <form id="myForm">
        <input type="text" name="id" readonly/><br />
        <input type="text" name="title" /><br />
        <select id="selectStartTime" onchange="changeCheckInTime(this, 'start', objEndTime)"></select>
        <select id="selectEndTime"></select>
        <a id="myClose">关闭</a>
        <a id="myInsert">新增</a>
        <a id="myDelete">删除</a>
        <a id="myUpdate">更新</a>
    </form>

</div>
</body>

</html>
